import 'dart:async';
import 'package:dio5_log/dio_log.dart';
import 'package:flutter/material.dart';
import 'package:hxdj/common/components/my_app_bottom.dart';
import 'package:hxdj/common/components/my_smart_refresher.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/my_common.dart';
import 'package:hxdj/common/my_constant.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:hxdj/home/address/select_address/select_address_page.dart';
import 'package:hxdj/home/home_order_widget.dart';
import 'package:hxdj/home/home_recommend_widget.dart';
import 'package:hxdj/home/home_viewmodel.dart';
import 'package:hxdj/common/routers/navigator.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //选择地址
  Widget _buildAddress() {
    return GestureDetector(
      onTap: () async {

        //去选择地址
        NavigatorUtils.pushParams(context, "${SelectAddressPage.routeName}?form=home");
      },
      child: Container(
        margin: const EdgeInsets.all(10.0),
        child: MyBorder(
          color: Colors.white,
          backgroundColor: Colors.white,
          radius: 10,
          child: viewModel?.addressModel == null
              ? Row(
                  children: [
                    // 有地址, 无地址, 图标, 大小 坐标不一样 一个小图标
                    Container(
                        padding: EdgeInsets.only(top: 20.w, bottom: 20.w, left: 8.5.w),
                        child: MyImage(imageName: "ic_address", width: 20.w)),

                    Container(
                        padding: EdgeInsets.only(left: 8.5.w),
                        child: MyText("请填写服务地址", textStyle: MyTextStyles.textBold14)),
                  ],
                )
              : Row(
                  children: [
                    // 有地址, 无地址, 图标, 大小 坐标不一样 一个小图标
                    Container(
                        padding: EdgeInsets.only(left: 25.w), child: MyImage(imageName: "ic_un_address", width: 20.w)),
                    //地址信息
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          //地址
                          Padding(
                            padding: EdgeInsets.only(
                              left: 12.w,
                              right: 12.w,
                              bottom: 5.w,
                              top: 20.w,
                            ),
                            child: Text(
                                (viewModel?.addressModel?.address ?? "") +
                                    (viewModel?.addressModel?.addressDetail ?? ""),
                                style: const TextStyle(fontSize: 15, color: Colors.black, height: 1.8)),
                          ),

                          //名字, 手机号
                          Container(
                            padding: EdgeInsets.only(left: 12.w, bottom: 20.w),
                            child: Row(
                              children: [
                                //名字
                                MyText(viewModel?.addressModel?.contacts ?? "", textStyle: MyTextStyles.textBold14),
                                Padding(
                                  padding: EdgeInsets.only(left: 8.w),
                                  child:
                                      MyText(viewModel?.addressModel?.mobile ?? "", textStyle: MyTextStyles.textBold14),
                                ),
                                //电话
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),

                    Container(
                        padding: const EdgeInsets.only(right: 15),
                        child: const MyImage(
                          imageName: "ic_arrow_right",
                          width: 6,
                          height: 9,
                        )),
                  ],
                ),
        ),
      ),
    );
  }



  HomeViewModel? viewModel;

  late RefreshController refreshController = RefreshController();
  late ScrollController scrollController = ScrollController();


  @override
  dispose() {
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    viewModel = Provider.of<HomeViewModel>(context, listen: false);

    viewModel?.context = context;
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      
      //是否测试开关环境
      bool isTest = CommonPlugin.sharedPreferences?.getBool(MyConstant.isTest) ?? false;

      if (isTest) {
        ///display overlay button 显示悬浮按钮
        showDebugBtn(context, btnColor: MyColours.appMain, btnSize: 50);
      }
      //请求当前权限
      await viewModel!.requestPermission();
      if (viewModel!.isPermission) {
        //有权限, 去定位
        viewModel!.startLocation();
      }

// ///cancel overlay button 取消悬浮按钮
// dismissDebugBtn();
// ///overlay button state of display 悬浮按钮展示状态
// debugBtnIsShow()
    });

  }

  _buildBody() {
    return Scaffold(
        backgroundColor: MyColours.bgColor,
        appBar: MyAppBar(
          title: "欢心到家",
          isBack: false,
          actionName: viewModel?.addressCity ?? "",
          rightWidget: Row(
            children: [
              Padding(
                padding: EdgeInsets.only(right: 5.w),
                child: const MyImage(imageName: "ic_location", width: 11, height: 14),
              ),
              Container(
                  constraints: BoxConstraints(
                    maxWidth: 100.w,
                  ),
                  child: Text(
                    viewModel!.state == ViewState.loading ? "定位中..." : viewModel?.addressCity ?? "定位失败",
                    overflow: TextOverflow.ellipsis,
                    maxLines: 2,
                    style: TextStyle(color: MyColours.text, fontSize: 13.sp),
                  ))
            ],
          ),
        ),
        body: MySmartRefresher(
          enablePullUp: false,
          enablePullDown: true,
          onRefresh: () async {
            await Future.delayed(const Duration(milliseconds: 500));
            refreshController.refreshToIdle();
            //请求数据
            viewModel!.requetsHomeData(isRefresh: true);
          },
          customChildWidget: SingleChildScrollView(
            child: Column(
              children: [
                //选择地址
                _buildAddress(),
                //今日推荐
                const HomeRecommendWidget(),
                //我的订单
                 HomeOrderWidget(viewModel: viewModel!),
                //底图
                MyAppBottom.buildBottom(),
              ],
            ),
          ),
          controller: refreshController,
          scrollController: scrollController,
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<HomeViewModel>(builder: (context, value, child) {
      viewModel?.context = context;

      switch (value.state) {
        case ViewState.loading:
        case ViewState.error:
          //定位中
          return Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                MyImage(
                    imageName: value.state == ViewState.error ? "ic_location_fail" : "ic_location_ing",
                    width: 100.w,
                    height: 100.w),
                Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: MyText(
                    value.state == ViewState.error ? "定位失败" : "定位中...",
                    fontSize: 18.sp,
                  ),
                ),
              ],
            ),
          );
        default:
          return _buildBody();
      }
    });
  }
}
